//
//  DisTypeGreatColCell.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/11.
//

import UIKit

class DisTypeGreatColCell: UICollectionViewCell {
    
    lazy var scrollView: UIScrollView = {
        let scro = UIScrollView.init(frame: .zero)
        scro.showsHorizontalScrollIndicator = true
        scro.showsVerticalScrollIndicator = false
        scro.delegate = self
        return scro
    }()
    
    lazy var infoView: DisTypeGreatInfoView = {
        return DisTypeGreatInfoView()
    }()
    
    var offsetX = 0.0
    
    var isFirst = true
    
    var currentItem = 0 {
        didSet {
            handleCurrentItem()
        }
    }
    
    var greatViewArr = [DisTypeGreatView]()
    
    var greatArr: [BookDetailModel]? {
        didSet {
            if let arr = greatArr, arr.count != 0 {
                for item in scrollView.subviews {
                    item.removeFromSuperview()
                }
                greatViewArr.removeAll()
                let showGreatArr = arr.count > 9 ? arr.sample(size: 9) : arr
                for i in 0..<(showGreatArr?.count ?? 0) {
                    let view = DisTypeGreatView()
                    view.frame = CGRect(x: CGFloat(i)*(scaleWidth(94)+12)+12, y: 0, width: (scaleWidth(94)+12), height: scaleWidth(140))
                    view.model = showGreatArr?[i]
                    greatViewArr.append(view)
                    scrollView.addSubview(view)
                }
                let w = CGFloat(showGreatArr?.count ?? 0)*(scaleWidth(94)+12)+12
                scrollView.contentSize = CGSize(width:ScreenW*0.55+w, height: 0)
                currentItem = 0
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(scrollView)
        addSubview(infoView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(12)
            make.left.bottom.right.equalTo(0)
        }
        infoView.snp.makeConstraints { (make) in
            make.bottom.equalTo(-16)
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.height.equalTo(108)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
extension DisTypeGreatColCell: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        (scrollView.subviews[(scrollView.subviews.count - 1)].subviews[0]).backgroundColor = .init(named: "red_FE95B4")
    }
    
    /// 滑动开始
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        offsetX = scrollView.contentOffset.x
    }
    
    /// 结束
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            scrollViewDidEndDecelerating(scrollView)
        }
    }
    
    /// 滑动结束
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if offsetX == scrollView.contentOffset.x { return }
        let direction = scrollView.contentOffset.x as CGFloat
        if (Int(direction/84)) >= (greatArr?.count ?? 0) {
            currentItem = (greatArr?.count ?? 0)-1
        }else {
            currentItem = Int(direction/84)
        }
    }
    
    func handleCurrentItem() {
        guard (greatArr?.count ?? 0) > 0 else {
            return
        }
        infoView.model = greatArr?[currentItem]
        for (i, v) in greatViewArr.enumerated() {
            if currentItem == i {
                v.bookImage.snp.updateConstraints { make in
                    make.size.equalTo(CGSize(width: scaleWidth(94), height: scaleWidth(140)))
                }
            }else {
                v.bookImage.snp.updateConstraints { make in
                    make.size.equalTo(CGSize(width: scaleWidth(84), height: scaleWidth(120)))
                }
            }
        }
        if isFirst {
            layoutIfNeeded()
        }else {
            UIView.animate(withDuration: 0.2) { [weak self] in
                self?.layoutIfNeeded()
            }
        }
    }
}

class DisTypeGreatView: UIView {
    
    lazy var bookImage: UIImageView = {
        let image = UIImageView(image: UIImage(named: "placeholder_cover_ver"))
        image.contentMode = .scaleAspectFill
        image.wn_cornerWithBorder(2)
        image.clipsToBounds = true
        return image
    }()
    
    lazy var disLabel: UILabel = {
        let label = UILabel()
        label.font = .wn_font(name: .bold, size: 9)
        label.textColor = .white
        label.backgroundColor = .init(named: "red_FE95B4")
        label.textAlignment = .center
        label.isHidden = true
        return label
    }()
    
    lazy var bookBtn: UIButton = {
         let btn = UIButton(type: .custom)
        btn.rx.tap.bind { [weak self] in
            self?.viewContainingController?.wn_pushBookVC(self?.model?.bookId ?? "")
        }.disposed(by: rx.disposeBag)
        return btn
    }()
    
    var model: BookDetailModel? {
        didSet {
            if let m = model {
                bookImage.wn_setupImg(m.coverUrl, placeHolder: "placeholder_cover_ver")
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(bookImage)
        bookImage.addSubview(disLabel)
        addSubview(bookBtn)
        bookImage.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.size.equalTo(CGSize(width: scaleWidth(84), height: scaleWidth(120)))
        }
        disLabel.snp.makeConstraints { (make) in
            make.top.equalTo(5)
            make.right.equalTo(-5)
            make.height.equalTo(14)
            make.width.equalTo(0)
        }
        bookBtn.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        wn_cornerWithBorder(4)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class DisTypeGreatInfoView: UIView {
    
    lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = .wn_font(name: .bold, size: 14)
        label.textColor = .black
        return label
    }()
    
    lazy var authorLabel: UILabel = {
        let label = UILabel()
        label.font = .wn_font(name: .bold, size: 11)
        label.textColor = .init(named: "gray_666666")
        return label
    }()
    
    lazy var desLabel: UILabel = {
        let label = UILabel()
        label.font = .wn_font(name: .bold, size: 11)
        label.textColor = .init(named: "gray_999999")
        label.numberOfLines = 3
        return label
    }()
    
    lazy var countBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitleColor(.black, for: .normal)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 10)
        btn.setImage(UIImage(named: "discover_see"), for: .normal)
        btn.imageView?.contentMode = .scaleAspectFit
        return btn
    }()
    
    var model: BookDetailModel? {
        didSet {
            if let m = model {
                nameLabel.text = m.name
                authorLabel.text = m.authorname
                desLabel.text = m.des
                countBtn.setTitle("\(m.readings)".wn_wan(), for: .normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .init(named: "white_F7F7F7")
        addSubview(nameLabel)
        addSubview(authorLabel)
        addSubview(countBtn)
        addSubview(desLabel)
        nameLabel.snp.makeConstraints { (make) in
            make.top.left.equalTo(6)
            make.right.equalTo(-6)
        }
        authorLabel.snp.makeConstraints { (make) in
            make.top.equalTo(nameLabel.snp.bottom).offset(4)
            make.left.equalTo(nameLabel.snp.left)
            make.right.equalTo(-6)
        }
        countBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(authorLabel.snp.centerY)
            make.right.equalTo(-6)
            make.height.equalTo(10)
        }
        desLabel.snp.makeConstraints { (make) in
            make.left.equalTo(nameLabel.snp.left)
            make.top.equalTo(authorLabel.snp.bottom).offset(4)
            make.right.equalTo(-6)
        }
        countBtn.layoutButton(style: .left, imageTitleSpace: 2)
        wn_cornerWithBorder(4)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
